package com.style_transfer.controller;

import com.style_transfer.model.U_image;
import com.style_transfer.service.impl.UImageServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/uimage")
public class UImageController {

    @Value("${file.upload.path}")
    private String fileUploadPath;

    @Value("${base_url}")
    private String base_url;

    @Autowired
    UImageServiceImpl uImageService;

    @PostMapping("/setuimage")
    public void setUImage(@RequestBody MultipartFile file, HttpServletRequest request) {
        U_image image = new U_image();
        File filePath = new File(fileUploadPath);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }

        String originalFileName = file.getOriginalFilename();
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        String username = originalFileName+"."+type;

        File result = new File(fileUploadPath,username);

        try {
            file.transferTo(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            String url = base_url+username;
            image.setUsername(username);
            image.setUrl(url);
            uImageService.setImage(image);
        }
    }

    public U_image getUImage(String username) {
        return uImageService.getImage(username);
    }
}
